/**
 * Created by IntelliJ IDEA.
 * User: mww
 * Date: 12-6-7
 * Time: 上午9:29
 * To change this template use File | Settings | File Templates.
 */
$(function(){
    $('#add').dialog({
        title:'添加',
        width:600,
        height:420,
        modal:true,
        closed:true,
        //draggable:false,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:okHandler
        },{
            text:'取消',
            handler:function(){
                $('#add').dialog('close');
            }
        }]
    });
    var action = $("#add_form").attr("action");
    function okHandler(){
        var categoryNode = $('#tt').tree('getSelected');
        if(categoryNode) {
            $("#formworkCategoryId").val(categoryNode.id);
        } else {
            $("#formworkCategoryId").val('');
        }

        var compositionA = $("#composition_a").val();
        var compositionB = $("#composition_b").val();
        var anum = 0;
        var bnum = 0 ;
        if(compositionA && $.trim(compositionA)!= '') {
            var cas = compositionA.split("_");
            anum = parseInt(cas[1]) ;
        }
        if(compositionB && $.trim(compositionB)!= '') {
            var cbs = compositionB.split("_");
            bnum =parseInt(cbs[1]);
        }
        var dataa = $("#formwork_container").data("a") ;
        var datab = $("#formwork_container").data("b") ;
        var astr = '';
        var bstr = '';
        if(anum > 0 && dataa) {
            for(var i=1 ;i<=anum;i++){
                var index = 'a'+i;
                var da = dataa[index] ;
                if(!da) {
                     continue;
                }
                if(astr != '') {
                   astr +="&";
                }
                astr += index+"="+da.category+"|"+da.quantity;
            }
        }
        if(bnum > 0 && datab) {
            for(var i=1 ;i<=bnum;i++){
                var index = 'b'+i;
                var db = datab[index] ;
                if(!db) {
                    continue;
                }
                if(bstr != '') {
                    bstr +="&";
                }
                bstr += index+"="+db.category+"|"+db.quantity;
            }
        }

        $('#add_form').form('submit',{
            url:action+"?"+astr+"&"+bstr,
            onSubmit: function(){
                if(!compositionA){
                    $.messager.alert('提示','请选择A面布局','info');
                    return false;
                }
                if(!dataa) {
                    $.messager.alert('提示','请选择A面布局所有区块类型','info');
                    return false;
                }

                for(var i=1 ;i<=anum;i++){
                    var da = dataa['a'+i] ;
                    if(!da) {
                        $.messager.alert('提示',"请选择A面布局"+i+"区块类型",'info');
                        return false;
                        break;
                    }
                    if(!da.category || da.category == '') {
                        $.messager.alert('提示',"请选择A面布局"+i+"区块类型",'info');
                        return false;
                        break;
                    }
                    if(!da.quantity || da.quantity == '') {
                        $.messager.alert('提示',"请填写A面布局"+i+"区块盘数量",'info');
                        return false;
                        break;
                    }
                }

                /*if(!compositionB){
                    $.messager.alert('提示','请选择B面布局','info');
                    return false;
                }
                if(!datab) {
                    $.messager.alert('提示','请选择B面布局所有区块类型','info');
                    return false;
                }
                for(var i=1 ;i<=bnum;i++){
                    var db = datab['b'+i] ;
                    if(!db) {
                        $.messager.alert('提示',"请选择B面布局"+i+"区块类型",'info');
                        return false;
                        break;
                    }
                    if(!db.category || db.category == '') {
                        $.messager.alert('提示',"请选择B面布局"+i+"区块类型",'info');
                        return false;
                        break;
                    }
                    if(!db.quantity || db.quantity == '') {
                        $.messager.alert('提示',"请填写B面布局"+i+"区块盘数量",'info');
                        return false;
                        break;
                    }
                }*/

                return $(this).form('validate');
            },
            success: function(data) {
                var data = eval('('+data+')');
                if (data.status == '1'){
                    $('#add').dialog('close');      // close the dialog
                    $.messager.alert(
                        '提示',
                        '操作成功',
                        'info'
                    );
                    $('#formworkcategory_tbl').datagrid('reload');
                } else {
                    $.messager.show({
                        title: '提示',
                        msg: data.msg
                    });
                }
            }

        });

    };

    $('#add_category').dialog({
        title:'添加',
        width:380,
        height:200,
        modal:true,
        closed:true,
        //draggable:false,
        buttons:[{
            text:'确定',
            iconCls:'icon-ok',
            handler:okCategoryHandler
        },{
            text:'取消',
            handler:function(){
                $('#add_category').dialog('close');
            }
        }]
    });

    function okCategoryHandler(){
        $('#add_category_form').form('submit',{
            onSubmit: function(){
                return $(this).form('validate');
            },
            success: function(data) {
                var data = eval('('+data+')');
                if (data.status == '1'){
                    $('#add_category').dialog('close');      // close the dialog
                    $('#tt').tree('reload');
                } else {
                    $.messager.show({
                        title: 'Error',
                        msg: data.msg
                    });
                }
            }

        });
    };

    $('#tt').tree({
        onClick: function(node){
            if(!node) {
                return;
            }
            $('#formworkcategory_tbl').datagrid({
                url:'listJson' ,
                queryParams:{categoryId:node.id}
            });
        }
    });

    $(".formworkcategory-add").live('click',function(){
        var selected = $('#tt').tree('getSelected');
        $('#add_category').dialog('open');
        $('#add_category_form').form("clear");
        $("#parentName").val("根节点") ;
        if (selected){
            $("#parentId").val(selected.id) ;
            $("#parentName").val(selected.text) ;
        }
    }) ;


    $(".formworkcategory-update").live('click',function(){
        var selected = $('#tt').tree('getSelected');

        if (selected){
            var parentNode =  $('#tt').tree('getParent',selected.target);
            $('#add_category').dialog('open').dialog('setTitle','编辑');
            $('#add_category_form').form("clear");
            if(parentNode) {
                $("#parentId").val(parentNode.id) ;
                $("#parentName").val(parentNode.text) ;
            }
            $("#category_name").val(selected.text) ;
            $("#category_id").val(selected.id) ;
        }
    }) ;
    $(".formworkcategory-delete").live('click',function(){
        var row = $('#tt').tree('getSelected');
        if (row){
            $.messager.confirm('提示','确定删除该记录?',function(r){
                if (r){
                    $.post($('#categoryDeleteUrl').val(),{id:row.id},function(result){
                        if (result.status == '1'){
                            $('#tt').tree('reload'); // reload the user data
                        } else {
                            $.messager.show({ // show error message
                                title: 'Error',
                                msg: result.msg
                            });
                        }
                    },'json');
                }
            });
        }

    } );

    function lstAdd(){
        var selected = $('#tt').tree('getSelected');
        if(!selected)  {
            $.messager.alert('提示',"请从左边选择模板分类",'info');
            return;
        }
        $('#add').dialog('open');
        $('#add_form').form("clear");
        _clearComposition();
        if (selected){
            $("#categoryId").val(selected.id) ;
            $("#categoryName").val(selected.text) ;
        }
    }

    function lstUpdate() {
        var selected = $('#formworkcategory_tbl').datagrid('getSelected');

        if (selected){
            var parentNode =  $('#tt').tree('getSelected');
            $('#add').dialog('open').dialog('setTitle','编辑');
            $('#add_form').form("clear");
            $('#add_form').form('load',selected);
            if(parentNode) {
                $("#categoryId").val(parentNode.id) ;
                $("#categoryName").val(parentNode.text) ;
            }
            _build(selected)
            $('#add').dialog('open')
        }
    }

    function lstDelete(){
        var row = $('#formworkcategory_tbl').datagrid('getSelected');
        if (row){
            $.messager.confirm('提示','确定删除该记录?',function(r){
                if (r){
                    $.post($('#deleteUrl').val(),{id:row.id},function(result){
                        if (result.status == '1'){
                            $('#formworkcategory_tbl').datagrid('reload'); // reload the user data
                        } else {
                            $.messager.show({ // show error message
                                title: '提示',
                                msg: '该模板已经被光交设备使用，无法删除'
                            });
                        }
                    },'json');
                }
            });
        }
    }

    $('#formworkcategory_tbl').datagrid({
        title:'模板列表',
        singleSelect:true,
        idField:'id',
        pagination:true,
        columns:[[
            {field:'name',title:'名称',width:100},
            {field:'description',title:'备注',width:100}
        ]],
        onBeforeLoad:function(){
            $(this).datagrid('rejectChanges');
        },
        onClickRow:function(rowIndex,rowData) {
            $('#btnedit').linkbutton('enable');
            $('#btnremove').linkbutton('enable');

        },
        rownumbers:true,
        toolbar:[{
            id:'btnadd',
            text:'添加',
            iconCls:'icon-add',
            handler:lstAdd
        },{
            id:'btnedit',
            text:'编辑',
            disabled:true,
            iconCls:'icon-edit',
            handler:lstUpdate
        },'-',{
            id:'btnremove',
            text:'删除',
            disabled:true,
            iconCls:'icon-remove',
            handler:lstDelete
        }]
    });

    $('#formwork_container').tabs({
        onSelect:tabSelectedHandler
    });

    function tabSelectedHandler(title) {
        if(title == 'A面') {
            setAarea()
        }
        if(title == 'B面') {
            setBarea()
        }
    }

    function setAarea() {
        var adatas = $("#formwork_container").data("a");
        if(!adatas) {
            return;
        }
        var node = $('#tta').tree('getSelected');
        if(!node) {
            return;
        }
        var selectedNumArea = adatas[node.id] ;
        if(!selectedNumArea){
            return;
        }
        var category = selectedNumArea.category;
        var quantity = selectedNumArea.quantity;
        if(category) {
            var _c =  category.split('at');
            var _category = $("#aCompositionContainer input[name='cp_area_num_category'][value='"+_c[0]+"']");
            var _area = _category.parent().prev().find("input[name='cp_area_num_horver']");
            _area.attr("checked",true);
            _category.attr("checked", true);
            $("#aCompositionContainer input[name='cp_area_num_terminal_category'][value='"+_c[1]+"']").attr("checked", true);
        }
        if(quantity) {
            $("#aCompositionContainer input[name='cp_area_quantity']").val(quantity)
        }
    }

    function setBarea() {
        var adatas = $("#formwork_container").data("b");
        if(!adatas) {
            return;
        }
        var node = $('#ttb').tree('getSelected');
        if(!node) {
            return;
        }
        var selectedNumArea = adatas[node.id] ;
        if(!selectedNumArea){
            return;
        }
        var category = selectedNumArea.category;
        var quantity = selectedNumArea.quantity;
        if(category) {
            var _c =  category.split('at');
            $("#bCompositionContainer input[name='cp_area_num_category'][value='"+_c[0]+"']").attr("checked", true);
            $("#bCompositionContainer input[name='cp_area_num_terminal_category'][value='"+_c[1]+"']").attr("checked", true);
        }
        if(quantity) {
            $("#bCompositionContainer input[name='cp_area_quantity']").val(quantity)
        }
    }

    //A面区块点击
    function aq(id) {
        if(id == 'a0') { //根节点
            $('#aCompositionContainer').html($('.select-a-composition').data('html'));
            $('.select-a-composition').show()
            $('.select-a-composition-ok').hide()
            $('.select-a-composition-cancel').hide()
            $('.select-a-composition-num-ok').hide();
        }else{
            $('#aCompositionContainer').html($('#composition_area_num_container').html())  ;
            $('.select-a-composition').hide();
            $('.select-a-composition-ok').hide();
            $('.select-a-composition-cancel').hide();
            $('.select-a-composition-num-ok').show();
            setAarea();
        }
    }

    //模板区块
    $('#tta').tree({
        data:[{text:'整体布局',id:'a0'}]    ,
        onClick: function(node){
            var id = node.id;
            aq(id)
        }
    });

    //清空布局设置
    function _clearComposition() {
        $("#formwork_container").removeData("a");
        $("#formwork_container").removeData("b") ;
        $("#aCompositionContainer").html('')
        $(".select-a-composition").removeData('html') ;
        $("#bCompositionContainer").html('')
        $(".select-b-composition").removeData('html') ;

        var node = $('#tta').tree('getRoot');
        if(node) {
            var children = $('#tta').tree('getChildren', node.target);
            if(children) {
                for(var i=0; i<children.length; i++){
                    $('#tta').tree('remove', children[i].target);
                }
            }
        }

        var nodeb = $('#ttb').tree('getRoot');
        if(nodeb){
            var childrenb = $('#ttb').tree('getChildren', nodeb.target);
            if(childrenb){
                for(var i=0; i<childrenb.length; i++){
                    $('#ttb').tree('remove', childrenb[i].target);
                }
            }
        }

        $('.select-a-composition').show();
        $('.select-a-composition-ok').hide() ;
        $('.select-a-composition-cancel').hide() ;
        $('.select-a-composition-num-ok').hide();

        $('.select-b-composition').show();
        $('.select-b-composition-ok').hide() ;
        $('.select-b-composition-cancel').hide() ;
        $('.select-b-composition-num-ok').hide();
    }

    //编辑时，构建模板布局和区块
    function _build(param) {
        _buildA(param['composition_a']);
        _buildDataA(param);

        _buildB(param['composition_b']);
        _buildDataB(param);
    }

    //构建A面模板布局
    function _buildA(compositionName){
        _buildTree('a',compositionName) ;
        _buildComposition('a',compositionName) ;
    }

    //构建B面模板布局
    function _buildB(compositionName){
        _buildTree('b',compositionName)  ;
        _buildComposition('b',compositionName);
    }

    //设置A面布局区块数据
    function _buildDataA(param) {
        var name = param["composition_a"];
        var cns = name.split("_") ;  //区块数
        var cnumber = cns[1];
        var datas = {}
        for(var i=1;i<=cnumber;i++){
            var _data = param['a'+i];
            datas['a'+i] = _data;
        }
        $("#formwork_container").data("a",datas);
    }

    //设置B面布局区块数据
    function _buildDataB(param) {
        var name = param["composition_b"];
        var cns = name.split("_") ;  //区块数
        var cnumber = cns[1];
        var datas = {}
        for(var i=1;i<=cnumber;i++){
            var _data = param['b'+i];
            datas['b'+i] = _data;
        }
        $("#formwork_container").data("b",datas);
    }

    //构建模板布局树。type表示a面或b面，值为a或b
    function _buildTree(type,compositionName) {

        var cns = compositionName.split("_") ;
        var cnumber = cns[1];
        var treedata = [cnumber]
        for(var kk=0;kk<cnumber;kk++){
            treedata[kk]={text:kk+1+'区',id:type+(kk+1)}
        }
        var _tree = $('#tt'+type) ;
        var node = _tree.tree('getRoot');
        var children = _tree.tree('getChildren', node.target);
        for(var i=0; i<children.length; i++){
            _tree.tree('remove', children[i].target);
        }
        _tree.tree('append',{
            parent: (node?node.target:null),
            data:treedata
        });
    }

    //构建布局，显示在页面上.
    function _buildComposition(type,compositionName) {
        $("#"+type+"CompositionContainer").load("getComposition",{name:compositionName},function(){
            $(".select-"+type+"-composition").data('html',$("#"+type+"CompositionContainer").html()) ;
        })
    }

    //A面区块选择分类和盘数量保存
    $('.select-a-composition-num-ok').click(function(){
        var node = $('#tta').tree('getSelected');
        var areaId = node.id;
        var categoryId = $("#aCompositionContainer input[name='cp_area_num_category']:checked").val();
        var quantity = $("#aCompositionContainer input[name='cp_area_quantity']").val();
        var terminalCategoryId = $("#aCompositionContainer input[name='cp_area_num_terminal_category']:checked").val();
        var adatas = $("#formwork_container").data("a");
        if(adatas) {
            adatas[areaId] = {category:categoryId+"at"+terminalCategoryId,quantity:quantity};
            $("#formwork_container").data("a",adatas);
        } else{
            adatas = {};
            adatas[areaId] ={category:categoryId+"at"+terminalCategoryId,quantity:quantity}
            $("#formwork_container").data("a",adatas)  ;
        }
        $.messager.alert('提示','设定成功！','info');
    });

    //选择A面模板
    $(".select-a-composition").click(function(){
        $('.select-a-composition').data('html',$('#aCompositionContainer').html())
        $(this).hide()
        $('.select-a-composition-ok').show() ;
        $('.select-a-composition-cancel').show() ;
        $('.select-a-composition-num-ok').hide();
        $("#aCompositionContainer").html($("#composition_list_container").val())
        //$("#aCompositionContainer").load("composition")
    })  ;

    //保存A面模板
    $('.select-a-composition-ok').click(function(){
        var a = $("input[name='composition_name']:checked")  ;
        if(a && a.length > 0) {
            var cname = a.val()
            $('#composition_a').val(cname) ;
            var c = a.parent().prev()
            $('#aCompositionContainer').empty();
            $(c).clone().appendTo("#aCompositionContainer");
            $('.select-a-composition').data('html',$('#aCompositionContainer').html())
            var cns = cname.split("_") ;
            var cnumber = cns[1];
            var treedata = [cnumber]
            for(var kk=0;kk<cnumber;kk++){
                treedata[kk]={text:kk+1+'区',id:'a'+(kk+1)}
            }
            var node = $('#tta').tree('getRoot');
            var children = $('#tta').tree('getChildren', node.target);
            for(var i=0; i<children.length; i++){
                $('#tta').tree('remove', children[i].target);
            }
            $('#tta').tree('append',{
                parent: (node?node.target:null),
                data:treedata
            });
        } else{
            $('#aCompositionContainer').html($('.select-a-composition').data('html'));
        }
        $('.select-a-composition').show()
        $('.select-a-composition-ok').hide()
        $('.select-a-composition-cancel').hide()
        $('.select-a-composition-num-ok').hide();
        $("#formwork_container").removeData("a");
    });



    //取消A面模板保存
    $('.select-a-composition-cancel').click(function(){
        $('#aCompositionContainer').html($('.select-a-composition').data('html'))
        $('.select-a-composition').show()
        $('.select-a-composition-ok').hide()
        $('.select-a-composition-cancel').hide()
        $('.select-a-composition-num-ok').hide();
    }) ;

    //B面区块点击
    function bq(id) {
        if(id == 'b0') { //根节点
            $('#bCompositionContainer').html($('.select-b-composition').data('html'));
            $('.select-b-composition').show()
            $('.select-b-composition-ok').hide()
            $('.select-b-composition-cancel').hide()
            $('.select-b-composition-num-ok').hide();
        }else{
            $('#bCompositionContainer').html($('#composition_area_num_container').html())  ;
            $('.select-b-composition').hide();
            $('.select-b-composition-ok').hide();
            $('.select-b-composition-cancel').hide();
            $('.select-b-composition-num-ok').show();
            setBarea();
        }
    }

    //B面模板区块
    $('#ttb').tree({
        data:[{text:'整体布局',id:'b0'}]    ,
        onClick: function(node){
            var id = node.id;
            bq(id)
        }
    });

    //B面区块选择分类和盘数量保存
    $('.select-b-composition-num-ok').click(function(){
        var node = $('#ttb').tree('getSelected');
        var areaId = node.id;
        var categoryId = $("#bCompositionContainer input[name='cp_area_num_category']:checked").val();
        var quantity = $("#bCompositionContainer input[name='cp_area_quantity']").val();
        var terminalCategoryId = $("#bCompositionContainer input[name='cp_area_num_terminal_category']:checked").val();
        var adatas = $("#formwork_container").data("b");
        if(adatas) {
            adatas[areaId] = {category:categoryId+"at"+terminalCategoryId,quantity:quantity};
            $("#formwork_container").data("b",adatas);
        } else{
            adatas = {};
            adatas[areaId] ={category:categoryId+"at"+terminalCategoryId,quantity:quantity}
            $("#formwork_container").data("b",adatas)  ;
        }
        $.messager.alert('提示','设定成功！','info');
    });

    //选择B面模板
    $(".select-b-composition").click(function(){
        $('.select-b-composition').data('html',$('#bCompositionContainer').html())
        $(this).hide()
        $('.select-b-composition-ok').show() ;
        $('.select-b-composition-cancel').show() ;
        $('.select-b-composition-num-ok').hide();
        $("#bCompositionContainer").html($("#composition_list_container").val())
    })  ;

    //保存B面模板
    $('.select-b-composition-ok').click(function(){
        var a = $("input[name='composition_name']:checked")  ;
        if(a) {
            var cname = a.val()
            $('#composition_b').val(cname) ;
            var c = a.parent().prev()
            $('#bCompositionContainer').empty();
            $(c).clone().appendTo("#bCompositionContainer");
            $('.select-b-composition').data('html',$('#bCompositionContainer').html())
            var cns = cname.split("_") ;
            var cnumber = cns[1];
            var treedata = [cnumber]
            for(var kk=0;kk<cnumber;kk++){
                treedata[kk]={text:kk+1+'区',id:'b'+(kk+1)}
            }
            var node = $('#ttb').tree('getRoot');
            var children = $('#ttb').tree('getChildren', node.target);
            for(var i=0; i<children.length; i++){
                $('#ttb').tree('remove', children[i].target);
            }
            $('#ttb').tree('append',{
                parent: (node?node.target:null),
                data:treedata
            });
        } else{
            $('#bCompositionContainer').html($('.select-b-composition').data('html'));
        }
        $('.select-b-composition').show()
        $('.select-b-composition-ok').hide()
        $('.select-b-composition-cancel').hide()
        $('.select-b-composition-num-ok').hide();
        $("#formwork_container").removeData("b");
    });

    //取消B面模板保存
    $('.select-b-composition-cancel').click(function(){
        $('#bCompositionContainer').html($('.select-b-composition').data('html'))
        $('.select-b-composition').show()
        $('.select-b-composition-ok').hide()
        $('.select-b-composition-cancel').hide()
        $('.select-b-composition-num-ok').hide();
    }) ;

    $('#formwork_container .area-hor').live('click',function(){
        var t = $(this);
        if(t.hasClass('area-hor-pan')) {
           $('#formwork_container .area-hor-root').attr('checked',true);
            var ter = $('#formwork_container .area-hor-ter:checked') ;
            if(!ter || ter.length == 0) {
                $('#formwork_container .area-hor-ter').attr('checked',true)
            }
            return;
        }
        if(t.hasClass('area-hor-ter')) {
            $('#formwork_container .area-hor-root').attr('checked',true);
            var pan = $('#formwork_container .area-hor-pan:checked') ;
            if(!pan || pan.length == 0) {
                $('#formwork_container .area-hor-pan').attr("checked",true);
            }
            return;
        }
        var ter = $('#formwork_container .area-hor-ter:checked') ;
        if(!ter || ter.length == 0) {
            $('#formwork_container .area-hor-ter').attr('checked',true)
        }
        var pan = $('#formwork_container .area-hor-pan:checked') ;
        if(!pan || pan.length == 0) {
            $('#formwork_container .area-hor-pan').attr("checked",true);
        }
    })
    $('#formwork_container .area-ver').live('click',function(){
        var t = $(this);
        if(t.hasClass('area-ver-pan')) {
            $('#formwork_container .area-ver-root').attr('checked',true);
            var ter = $('#formwork_container .area-ver-ter:checked') ;
            if(!ter|| ter.length == 0) {
               $('#formwork_container .area-ver-ter').attr('checked',true);
            }
            return;
        }
        if(t.hasClass('area-ver-ter')) {
            $('#formwork_container .area-ver-root').attr('checked',true);
            var pan = $('#formwork_container .area-ver-pan:checked') ;
            if(!pan || pan.length == 0) {
                $('#formwork_container .area-ver-pan').attr('checked',true);
            }
            return;
        }
        var ter = $('#formwork_container .area-ver-ter:checked') ;
        if(!ter || ter.length == 0) {
            $('#formwork_container .area-ver-ter').attr('checked',true);
        }
        var pan = $('#formwork_container .area-ver-pan:checked') ;
        if(!pan|| pan.length == 0) {
            $('#formwork_container .area-ver-pan').attr('checked',true);
        }
    })
})

